import os
import random
import time

suffix_tuple = ("jpg", "png", "txt", "mp4", "csv", "json", "xlsx", "pdf", "gif", "mp3")  # 文件后缀


def create_dir():
    """
    创建目录
    :return:
    """
    log("在当前目录下依次创建/greedy/python/basic_learn/basic_ai目录。")
    pwd = os.getcwd()  # 获取当前目录
    os.makedirs(pwd + "/greedy/python/basic_learn/basic_ai")
    log("目录创建完成。。。")


def __generate_file__(path, num):
    """
    随机生成文件
    :return:
    """
    for i in range(0, num):
        timestamp_str = str(time.time_ns())  # 获取时间抽
        word_lst = ["a", "b", "c", "d", "e", "f"]  # 单词列表
        file_name = timestamp_str + word_lst[random.randint(0, len(word_lst) - 1)] + "贪心学院" + "." + suffix_tuple[
            random.randint(0, len(suffix_tuple) - 1)]
        log(file_name)
        file_name = path + os.sep + file_name
        fd = os.open(file_name, os.O_CREAT)
        os.close(fd)


def find_dir(path):
    """
    遍历所有目录
    :param path:
    :return:
    """
    dirs = os.listdir(path)
    for item in dirs:
        # 存在目录就一直往下找
        if os.path.isdir(path + os.sep + item):
            print("{}是目录,即将随机创建10个文件".format(item))
            log("即将在目录{}下随机创建10个文件".format(item))
            __generate_file__(os.path.join(path, item), 10)
            find_dir(path + os.sep + item)
        else:
            print("{}不是目录".format(item))
            continue
    log("随机生成文件结束。。。")


def del_file(suffix, keyword="贪心学院", dirname="greedy"):
    """
    删除指定目录下符合条件的文件
    :param suffix:
    :param keyword:
    :param dirname:
    :return:
    """
    pwd = os.getcwd()
    dir_path = os.path.join(pwd, dirname)
    file_lst = os.listdir(dir_path)
    for file in file_lst:
        file_path = os.path.join(dir_path, file)
        if os.path.isfile(file_path):
            # 是文件才执行删除操作
            # 判断文件的关键字
            if file.find(keyword) > 0:
                # 判断后缀
                if suffix in suffix_tuple:
                    if file.find("." + suffix) > 0:
                        # 删除文件
                        print("删除文件%s", file_path)
                        log("删除文件{}".format(file_path))
                        os.remove(file_path)


def log(message):
    """
    往文件中追加日志，如果文件不存在，就创建文件
    :return:
    """
    with open("file_operation.log", "a+", 1024, encoding="UTF-8", newline="\r\n") as file_obj:
        file_obj.write(message + "\r")


if __name__ == "__main__":
    # log("1、创建目录")
    # create_dir()
    # log("2、在新创建的所有的文件夹下随机生成1到10个文件")
    # find_dir(os.getcwd())
    log("3、删除指定目录下的文件")
    del_file("png")
